import time
import re
import urllib.parse

from selenium import webdriver
from selenium.webdriver.common.by import By


def main():
    chrome_options = webdriver.ChromeOptions()
    service = webdriver.ChromeService(executable_path='./chromedriver.exe')
    driver = webdriver.Chrome(service=service, options=chrome_options)
    driver.get("https://top.baidu.com/board?tab=movie")
    # 方式一
    # elements = driver.find_elements(By.CLASS_NAME, "category-wrap_iQLoo ")
    # 方式二
    elements = driver.find_elements(By.CSS_SELECTOR, ".category-wrap_iQLoo ")
    print(f'the length of elements is {len(elements)}')
    for element in elements:
        a = element.find_element(By.CLASS_NAME, "trend_2RttY")
        url = a.get_attribute('href')
        word_list = re.split("words=", url)
        title = word_list[-1]
        decoded_title = urllib.parse.unquote(title)

        div = element.find_element(By.CLASS_NAME, "hot-index_1Bl1a")
        hot_index = div.text

        print(f'电影名称:{decoded_title}, 热搜指数:{hot_index}')

    time.sleep(10)
    # 关闭浏览器
    driver.close()


if __name__ == '__main__':
    main()
